﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Collections;
using System.Data;
using System.Threading;

using Castle.Core.Logging;

using InfoGenerateSystem.Domain;
using InfoGenerateSystem.Service.Interfaces;
using InfoGenerateSystem.Component;
using InfoGenerateSystem.Persistence.IDao;
using InfoGenerateSystem.Core.Utils;

namespace InfoGenerateSystem.Service.Implements
{
    /// <summary>
    /// 网页截图服务类
    /// 
    /// 创建人:     王昊
    /// 创建时间:   2009-04-28
    /// 
    /// </summary>
    public class WebPageToImage : AbstractConfigService, IWebPageToImage
    {
        private IGenericDao _dao = ServiceHelper.GetService(typeof(IGenericDao)) as IGenericDao;
        private ILogger _log = ServiceHelper.GetService(typeof(ILogger)) as ILogger;

        private static IList<ImageWebPage> webPageList;

        public void GoSnagImage()
        {
            //SnagAccountImages();
            SnagSecurityImages();
        }

        private void SnagAccountImages()
        {
            Int64 labelID = 0;

            IList<TblbLabel> labelList = _dao.Query<TblbLabel>("TblbLabel.FindAllAccountPicLabels", null);

            String configFileName = Directory + ConfigFilePath;

            SnagConfig sc = ConfigLoader.LoadSnagConfig(configFileName);
            if (webPageList == null)
            {
                webPageList = ConfigLoader.LoadWebPagesConfigForSnag(configFileName);
            }

            DataTable accountTable = _dao.QueryForTable("TblbAccountGraphy.FindAll", null).Tables[0];

            Int32 scrWidth = sc.ScrWidth;
            Int32 scrHeight = sc.ScrHeight;
            Int32 imgWidth = sc.ImageWidth;
            Int32 imgHeight = sc.ImageHeight;

            foreach (ImageWebPage webPage in webPageList)
            {

                String webUrl = webPage.Url;

                foreach (TblbLabel lbl in labelList)
                {
                    try
                    {
                        labelID = lbl.SECID;
                        //Thread ta = new Thread(new ThreadStart(delegate()
                        //{
                        if (lbl.LABELTYPEID == 15 || lbl.LABELTYPEID == 16)
                        {
                            InsertAccountGraphy(accountTable, scrWidth, scrHeight, imgWidth, imgHeight, webPage, lbl.SECID, lbl.NAME);
                        }
                        //}));
                        //ta.SetApartmentState(ApartmentState.STA);
                        //ta.Start();
                    }
                    catch (Exception ex)
                    {
                        _log.Error(Convert.ToString(labelID));
                        _log.Error(ex.Message);
                        _log.Error(ex.StackTrace);

                        continue;
                    }
                }
            }
        }

        private void SnagSecurityImages()
        {
            Int64 labelID = 0;

            IList<TblbLabel> labelList = GetLabelList(Directory, ConfigFilePath);

            String configFileName = Directory + ConfigFilePath;

            SnagConfig sc = ConfigLoader.LoadSnagConfig(configFileName);
            if (webPageList == null)
            {
                webPageList = ConfigLoader.LoadWebPagesConfigForSnag(configFileName);
            }

            DataTable stockTable = _dao.QueryForTable("SecurityInfo.FindAllStockForSnag", null).Tables[0];
            DataTable fundTable = _dao.QueryForTable("SecurityInfo.FindAllFundForSnag", null).Tables[0];
            DataTable warrantTable = _dao.QueryForTable("SecurityInfo.FindAllWarrantForSnag", null).Tables[0];
            DataTable bondTable = _dao.QueryForTable("SecurityInfo.FindAllBondForSnag", null).Tables[0];

            Int32 scrWidth = sc.ScrWidth;
            Int32 scrHeight = sc.ScrHeight;
            Int32 imgWidth = sc.ImageWidth;
            Int32 imgHeight = sc.ImageHeight;

            foreach (ImageWebPage webPage in webPageList)
            {
                String webUrl = webPage.Url;

                foreach (TblbLabel lbl in labelList)
                {
                    try
                    {
                        labelID = lbl.SECID;
                        //Thread ta = new Thread(new ThreadStart(delegate()
                        //{
                        if (lbl.LABELTYPEID == 20)
                        {
                            InsertSecurityGraphy(stockTable, scrWidth, scrHeight, imgWidth, imgHeight, webPage, lbl.SECID, lbl.NAME);
                        }
                        else if (lbl.LABELTYPEID == 21)
                        {
                            InsertSecurityGraphy(fundTable, scrWidth, scrHeight, imgWidth, imgHeight, webPage, lbl.SECID, lbl.NAME);
                        }
                        else if (lbl.LABELTYPEID == 22)
                        {
                            InsertSecurityGraphy(warrantTable, scrWidth, scrHeight, imgWidth, imgHeight, webPage, lbl.SECID, lbl.NAME);
                        }
                        else if (lbl.LABELTYPEID == 23)
                        {
                            InsertSecurityGraphy(bondTable, scrWidth, scrHeight, imgWidth, imgHeight, webPage, lbl.SECID, lbl.NAME);
                        }
                        //}));
                        //ta.SetApartmentState(ApartmentState.STA);
                        //ta.Start();
                    }
                    catch (Exception ex)
                    {
                        _log.Error(Convert.ToString(labelID));
                        _log.Error(ex.Message);
                        _log.Error(ex.StackTrace);

                        continue;
                    }
                }
            }
        }

        private void InsertAccountGraphy(DataTable accountTable, Int32 scrWidth, Int32 scrHeight, Int32 imgWidth, Int32 imgHeight, ImageWebPage webPage, Int64 labelID, String labelName)
        {
            foreach (DataRow accountInfo in accountTable.Rows)
            {
                String url = String.Empty;
                try
                {
                    Int64 accountCode = Convert.ToInt64(accountInfo["ACCOUNTCODE"]);

                    TblbLabelParam labelParam = _dao.Find("TblbLabelParam.FindByLABELID", labelID) as TblbLabelParam;

                    String title = accountCode + "-" + labelName + "-" + DateTime.Now.ToString("yyyy-MM-dd") + ".jpg";
                    url = String.Format(webPage.Url, labelID, String.Empty, accountCode);
                    //WebToImageGetter thumb = new WebToImageGetter(url, scrWidth, scrHeight, Convert.ToInt32(labelParam.PICWIDTH), Convert.ToInt32(labelParam.PICHEIGHT));
                    WebToImageGetter thumb = new WebToImageGetter(url, scrWidth, scrHeight, imgWidth, imgHeight);
                    Bitmap x = thumb.GetBitmap();

                    MemoryStream imgStream = new MemoryStream();
                    x.Save(imgStream, ImageFormat.Jpeg);
                    Byte[] bytes = { };
                    bytes = imgStream.ToArray();

                    TblbAccountGraphyData grph = new TblbAccountGraphyData();
                    grph.LABELID = labelID;
                    grph.FILENAME = title;
                    grph.NR = bytes;
                    grph.ACCOUNTCODE = accountCode;
                    grph.OPERATIONDATE = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    grph.LASTEDITDATE = DateTime.Now;

                    _dao.Insert("TblbAccountGraphyData.Insert", grph);
                    //x.Save(Directory + "\\Temp\\Snap-" + title + ".jpg", ImageFormat.Jpeg);
                    imgStream.Close();
                    imgStream.Dispose();

                    System.GC.Collect();
                }
                catch (Exception ex)
                {
                    _log.Error(Convert.ToString(labelID));
                    _log.Error(String.Format("url, scrWidth, scrHeight, imgWidth, imgHeight={0},{1},{2},{3},{4}", url, scrWidth, scrHeight, imgWidth, imgHeight));
                    _log.Error(ex.Message);
                    _log.Error(ex.StackTrace);
                }
            }
        }

        private void InsertSecurityGraphy(DataTable securityTable, Int32 scrWidth, Int32 scrHeight, Int32 imgWidth, Int32 imgHeight, ImageWebPage webPage, Int64 labelID, String labelName)
        {
            foreach (DataRow securityInfo in securityTable.Rows)
            {
                String url = String.Empty;
                try
                {
                    String secuCode = Convert.ToString(securityInfo["ZQDM"]);
                    String secuName = Convert.ToString(securityInfo["ZQJC"]);
                    Int32 secuType = Convert.ToInt32(securityInfo["STOCKTYPE"]);

                    TblbLabelParam labelParam = _dao.Find("TblbLabelParam.FindByLABELID", labelID) as TblbLabelParam;

                    String title = secuCode + "-" + labelName + "-" + DateTime.Now.ToString("yyyy-MM-dd") + ".jpg";
                    url = String.Format(webPage.Url, labelID, secuCode, String.Empty);
                    //WebToImageGetter thumb = new WebToImageGetter(url, scrWidth, scrHeight, Convert.ToInt32(labelParam.PICWIDTH), Convert.ToInt32(labelParam.PICHEIGHT));
                    WebToImageGetter thumb = new WebToImageGetter(url, scrWidth, scrHeight, imgWidth, imgHeight);
                    Bitmap x = thumb.GetBitmap();

                    MemoryStream imgStream = new MemoryStream();
                    x.Save(imgStream, ImageFormat.Jpeg);
                    Byte[] bytes = { };
                    bytes = imgStream.ToArray();

                    TblbStockIndexesGraphyData grph = new TblbStockIndexesGraphyData();
                    grph.LABELID = labelID;
                    grph.FILENAME = title;
                    grph.NR = bytes;
                    grph.STOCKCODE = secuCode;
                    grph.STOCKNAME = secuName;
                    grph.STOCKTYPE = secuType;
                    grph.OPERATIONDATE = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    grph.LASTEDITDATE = DateTime.Now;

                    _dao.Insert("TblbStockIndexesGraphyData.Insert", grph);
                    //x.Save(Directory + "\\Temp\\Snag-" + title + ".jpg", ImageFormat.Jpeg);
                    imgStream.Close();
                    imgStream.Dispose();

                    System.GC.Collect();
                }
                catch (Exception ex)
                {
                    _log.Error(Convert.ToString(labelID));
                    _log.Error(String.Format("url, scrWidth, scrHeight, imgWidth, imgHeight={0},{1},{2},{3},{4}", url, scrWidth, scrHeight, imgWidth, imgHeight));
                    _log.Error(ex.Message);
                    _log.Error(ex.StackTrace);
                }
            }
        }

        public IList<ImageWebPage> GetWebPageList()
        {
            return GetWebPageList(Directory, ConfigFilePath);
        }

        public IList<ImageWebPage> GetWebPageList(String directory, String configFilePath)
        {
            if (webPageList == null)
            {
                webPageList = ConfigLoader.LoadWebPagesConfigForSnag(directory + configFilePath);
            }
            return webPageList;
        }

        public IList<ImageWebPage> ReloadWebPageList()
        {
            webPageList = ConfigLoader.LoadWebPagesConfigForSnag(Directory + ConfigFilePath);
            return webPageList;
        }

        public SnagConfig GetSnagConfig()
        {
            return ConfigLoader.LoadSnagConfig(Directory + ConfigFilePath);
        }

        public void SaveSnagConfig(SnagConfig sc, IList<TblbLabel> labelList, IList<ImageWebPage> webPageList)
        {
            ConfigSaver.SaveSnagConfig(Directory + ConfigFilePath, sc, labelList, webPageList);
        }
    }
}
